import React, { useState, useEffect, useContext  } from 'react';
import { Table, Tag, Button, Popconfirm, message,Space, Pagination, Form, Input, Select,DatePicker, Modal, Row, Col, TreeSelect, Radio,Tree,InputNumber ,Tooltip   } from 'antd';
import { DictContext } from '../../../context/context';
import { SearchOutlined , RedoOutlined, PlusOutlined, EditOutlined, DeleteOutlined} from '@ant-design/icons';
import DictTag from '../../../components/DictTag';

import { listConfig, addConfig, updateConfig, delConfig, getConfig, getConfigKey, refreshCache } from '../../../api/system/config';

function Config() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [queryParams, setQueryParams] = useState({ pageNum: 1, pageSize: 10 });
  const [searchForm] = Form.useForm();
  const [formAdd] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [single, setSingle] = useState(true);
  const [multiple, setMultiple] = useState(true);
  const [ids, setIds] = useState([]);
      const { useDict} = useContext(DictContext);
      const { sys_yes_no } = useDict('sys_yes_no');
      const [title, setTitle] = useState('');

  const onSelectChange = newSelectedRowKeys => {
    //console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
    setSingle(newSelectedRowKeys.length != 1) ;
    setMultiple(!newSelectedRowKeys.length);
    setIds(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const columns =[
    {
      title: '参数主键',
      dataIndex: 'configId',
      key: 'configId',
      width: 100,
    },
    {
      title: '参数名称',
      dataIndex: 'configName',
      key: 'configName',
    },
    {
        title:'参数键名',
        dataIndex:'configKey',
        key:'configKey'
    },
    {
      title: '参数键值',
      dataIndex: 'configValue',
      key: 'configValue',
    },
    {
      title: '系统内置',
      dataIndex: 'configType',
      key: 'configType',
      render: text => <DictTag type="sys_yes_no" value={text} options={sys_yes_no} />,
      width: 100,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
        align: 'center',
        width: 200,
        render: (text, record) => {
            return (
                        <Space size="middle">
                        <Button type='link' onClick={() => handleUpdate(record)}>修改</Button>
                        <Popconfirm
                            title="删除确认"
                            description={`是否确认删除参数编号为 ${record.configId} 的数据项？`}
                            onConfirm={() => handleDelete(record)}
                            onCancel={delCancel}
                            okText="确定"
                            cancelText="取消"
                        >
                        <Button type='link'>删除</Button>
                        </Popconfirm>
                        </Space>
            );
        }
    }
  ];

  const handleUpdate = record => {
    setTitle('修改');
    const configId = record.configId || ids;
    getConfig(configId).then(res => {
      if (res.code === 200) {
        formAdd.setFieldsValue(res.data);
        setOpen(true);
      } else {
        message.error(res.msg);
      }
  });
}

  const handleDelete = record => {
    const configId = record.configId || ids;
    delConfig(configId).then(res => {
      if (res.code === 200) {
        message.success(res.msg);
        handleQuery();
      } else {
        message.error(res.msg);
      }
    }).catch(err => {
       //console.log('====config del======',err) 
    });
    ;
  }

  const delCancel = e => {
    console.log(e);
    //message.error('Click on No');
  }

  useEffect(() => {
    handleQuery();
  }, [queryParams]);

const handleQuery = () => {
    listConfig(queryParams).then(res => {
      if (res.code === 200) {
        setData(res.rows);
        setTotal(res.total);
      } else {
        message.error(res.msg);
      }
    })
}

const onChange = (pagination, filters, sorter) => {
    setQueryParams({
      ...queryParams,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    });
}

const handleOk = () => {
    formAdd.validateFields().then(values => {
        if (formAdd.getFieldValue().configId === undefined) {
            addConfig(formAdd.getFieldValue()).then(res => {
                if (res.code === 200) {
                    message.success(res.msg);
                    setOpen(false);
                    handleQuery();
                } else {
                    message.error(res.msg);
                }
            })
        } else {
            updateConfig(formAdd.getFieldValue()).then(res => {
                if (res.code === 200) {
                    message.success(res.msg);
                    setOpen(false);
                    handleQuery();
                } else {
                    message.error(res.msg);
                }
            })
        }
    });
}

const handleCancel = () => {
    setOpen(false);
    formAdd.resetFields();
}

const handleAdd = () => {
    setTitle('新增');
    setOpen(true);
}

  return (
    <div>
        <Row gutter={[16, 16]}  style={{marginBottom: '20px', width: '100%'}}>
            <Col span={24}>
                <Form form={searchForm} layout="inline">
                    <Form.Item label="参数名称" name="configName">
                        <Input placeholder="请输入参数名称" />
                    </Form.Item>
                    <Form.Item label="参数键名" name="configKey">
                        <Input placeholder="请输入参数键名" />
                    </Form.Item>
                    <Form.Item label="系统内置" name="configType">
                        <Select placeholder="请选择系统内置" options={sys_yes_no.value} style={{width: '200px'}}/>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" onClick={handleQuery}>查询</Button>
                    </Form.Item>
                </Form>
            </Col>
        </Row>
        <Row gutter={[16, 16]}  style={{marginBottom: '20px', width: '100%'}}>
            <Col span={24}>
            <Space>
                <Button color="primary"  variant="filled" onClick={handleAdd} icon={<PlusOutlined />}>新增</Button>
                <Button color="green"  variant="filled" onClick={handleUpdate} icon={<EditOutlined /> } disabled={single}>修改</Button>
                <Button color="red"  variant="filled" onClick={handleDelete} icon={<DeleteOutlined />} disabled={multiple}>删除</Button>
                <Button color="orange"  variant="filled" onClick={handleAdd} icon={<RedoOutlined />}>刷新</Button>
                </Space>
            </Col>
        </Row>
        <Table loading={loading} rowSelection={rowSelection} dataSource={data} columns={columns} pagination={{ pageSize: queryParams.pageSize, current: queryParams.pageNum ,showQuickJumper: true, pageSizeOptions: [3, 5, 10, 20], showSizeChanger: true, total: total, showTotal: total => `共 ${total} 条`}} rowKey={record => record.configId} onChange={onChange}/>
            <Modal title={title} open={open} onOk={handleOk} onCancel={handleCancel}>
                <Form form={formAdd} layout="horizontal"  labelCol={{ span: 5 }}>
                    <Form.Item label="参数名称" name="configName">
                        <Input placeholder="请输入参数名称" />
                    </Form.Item>
                    <Form.Item label="参数键名" name="configKey">
                        <Input placeholder="请输入参数键名" />
                    </Form.Item>
                    <Form.Item label="参数键值" name="configValue">
                        <Input placeholder="请输入参数键值" />
                    </Form.Item>
                    <Form.Item label="系统内置" name="configType">
                        <Radio.Group options={sys_yes_no.value} />
                    </Form.Item>
                    <Form.Item label="备注" name="remark">
                        <Input.TextArea placeholder="请输入备注" />
                    </Form.Item>
                </Form>
            </Modal>
    </div>
  );
}

export default Config;